package com.appspot.seqpop.model;

import java.io.Serializable;

import org.slim3.datastore.Model;
import org.slim3.datastore.ModelRef;

@Model(schemaVersion = 1)
public class AlignedSequence extends Sequence implements Serializable {

    private static final long serialVersionUID = 1L;

    public static final int INVALID_POSITION = -1;
    
    private ModelRef<Alignment> alignmentRef = new ModelRef<Alignment>(Alignment.class);

    private int position = INVALID_POSITION;

    public AlignedSequence() {
    }

    public AlignedSequence(Sequence sequence, int position) {
        super(sequence.getDescription(), sequence.getSequence());
        setPosition(position);
    }
    
    public ModelRef<Alignment> getAlignmentRef() {
        return this.alignmentRef;
    }
    
    public int getPosition() {
        return this.position;
    }

    public void setPosition(int position) {
        this.position = position;
    }
    
    @Override
    public String getSequence() {
        if (getPosition() == INVALID_POSITION) {
            return super.getSequence();
        }
        
        StringBuilder sequence = new StringBuilder();
        int position = getPosition();
        while (--position >= 0) {
            sequence.append(Sequence.GAP);
        }
        sequence.append(super.getSequence());
        Alignment alignment = getAlignmentRef().getModel();
        int tail = alignment.getLength() - getPosition() - getLength();
        while (--tail >= 0) {
            sequence.append(Sequence.GAP);
        }
        return sequence.toString();
    }
}
